package com.mystudy.leetcode.problem.other.p_7;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @program: infoalgorithm
 * @description: 整数反转
 * @author: zhouzhilong
 * @create: 2019-07-29 16:21
 **/
public class Solution {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(Solution.class);

    @Test
    public void test() {
        int reverse = reverse2(0);
        LOGGER.debug("reverse = [{}]", reverse);
    }


    public int reverse(int x) {
        if (x >= 0 && x <= 9) {
            return x;
        }
        int flag = 1;
        if (x < 0) {
            flag = -1;
        }
        List<Integer> list = new ArrayList<>();

        int temp = x;
        int count = 0;
        while (temp != 0) {
            int result = temp % 10;
            if (result < 0) {
                result = -1 * result;
            }
            list.add(result);
            temp = temp / 10;
            count++;
        }
        LOGGER.debug("list = [{}]", list);
        StringBuffer sb = new StringBuffer();
        for (Integer integer : list) {
            sb.append(integer);
        }
        long result = flag * Long.valueOf(sb.toString());
        LOGGER.debug("result = [{}]", result);
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
            return 0;
        } else {
            return (int) result;
        }
    }


    public int reverse2(int x) {
        int flag = 1;
        if (x < 0) {
            flag = -1;
        }
        Queue<Integer> queue = new LinkedList<>();
        int temp = x;
        while(temp != 0){
            int result = temp%10;
            if(result <0){
                result = -1*result;
            }
            queue.offer(result);
            temp = temp/10;
        }
        long result  = 0;
        while(!queue.isEmpty()){
            Integer pop = queue.poll();
            result = result*10+pop;
            LOGGER.debug("result = [{}]",result);
        }
        result = flag*result;
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
            return 0;
        } else {
            return (int) result;
        }
    }
}